﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace Dixon.Jscp
{
    /// <summary>
    /// A JSCP request handler that serves compiled JavaScript client
    /// pages
    /// </summary>
    class JSClientPageHandler : IHttpHandler
    {

        #region IHttpHandler Members


        /// <summary>
        /// The pattern used for matching page parameters
        /// </summary>
        private Regex pagePattern = new Regex("^page\\d*$");


        /// <summary>
        /// Determines whether or not this handler
        /// can be used in a pool. In the case of JSClientPageHandler,
        /// this method always retuens true.
        /// </summary>
        public bool IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// <para>
        /// Servers all pages specified in the HTTP request with
        /// page[digit] as the key.
        /// </para>
        /// <para>
        /// Example:
        /// ?page1=Examples/Example1.xml&page2=Employees.xml
        /// </para>
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            var pages =
                from key
                    in context.Request.QueryString.AllKeys
                where pagePattern.IsMatch(key)
                select context.Request.QueryString[key];

            var configuration = new WebConfiguration(context);
            
            foreach (string pageName in pages)
            {
                var page = new JSClientPage(configuration, pageName);
                page.Output(context.Response.OutputStream, context.Response.Output.Encoding);
                context.Response.Output.WriteLine();
                context.Response.Output.Flush();
            }
            context.Response.OutputStream.Flush();
        }

        #endregion
    }
}
